<?php
namespace control;

/*
*生产线档案类
*/

class productLineClass extends adIndexClass
{
    private const page = 'productLine';
    private const table = 'product_line';
    private const title = '生产线档案';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "生产线编号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'workshop'  => [
                        'name'  => '生产车间',
                        'width' => 250,
                    ],
                    'name'         => [
                        'name'  => '生产线',
                        'width' => 250,
                    ],
                    'staffId'          => [
                        'name'  => '生产线负责人',
                        'width' => 200,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '创建日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "生产线编号" => text(array("name" => "orderNo")),
                    "生产车间"   => text(array("name" => "workshop")),
                    "生产线"   => text(array("name" => "name")),
                ],
                [
                    "创建日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['启用','停用']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'启用'})\" class='spanButton'>启用</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'停用'})\" class='spanButton'>停用</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "workshop" => $this->post('workshop'),
            "name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
        );
        $and = " and coid = '".self::$coid."'";
        if ($this->post('time')) {
            $timeArr = explode(' ~ ', $this->post('time'));
            $and .= " and date(time) >='{$timeArr[0]}' and date(time) <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'staffId':
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取生产线名称
     * @param $id
     * @param string $char
     * @return string
     */
    public static function getName($id,$char=''): string
    {
        $line = query(self::table,"id ='$id'");
        return implode($char,[$line['workshop'],$line['name']]);
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "生产线编号：" => text(["name" => "orderNo", 'class' => 'text', "value" => $info['orderNo']]),
                    must . "生产车间：" =>repeatSelect(array('name'=>'selectName','value'=>$info['workshop'],'sqlForm'=>self::table." where coid = '".self::$coid."'",'sqlField'=>'workshop','title'=>'生产车间','change'=>'setWorkshop')).
                        text(["name" => "workshop", 'class' => 'text', "value" => $info['workshop']]),
                ],
                [
                    must . "生产线：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    "生产线负责人：" => selectMultiple(array('table' => 'staff', 'where'=>"state !='离职'","title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'staffId', 'value' => $info['staffId'])),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $html.=<<<efo
<script>
function setWorkshop(e){
    $(e).siblings("[name='workshop']").val(e.value);
}
</script>
efo;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

    /**
     * 编辑
     * @return bool|string
     */
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'name' => $this->post('name'),
            'orderNo' => $this->post('orderNo'),
            'workshop' => $this->post('workshop'),
            'staffId' => $this->post('staffId'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'name' => '生产线',
            'orderNo' => '生产编号',
            'workshop' => '生产车间',
        ];
        $rules = [
            'name' => 'required',
            'orderNo' => 'required',
            'workshop' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and id !='$id' and orderNo = '$field[orderNo]'"))>0){
            $json['warn'] = "已存在此生产编号";
        }elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and id !='$id' and workshop = '$field[workshop]' and name = '$field[name]'"))>0){
            $json['warn'] = '已存在此名称的生产线';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                    'state' => '启用',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $state = $info['state'] == '停用' ? '启用' : '停用';
                $button[] = [
                    "name" => $state,
                    "type" => "点击事件",
                    'title' => '修改状态',
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$state}'})",
                ];
            }
            if ($this->power(self::page,'del') && $info['state'] =='停用'){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "生产线编号" => $info['orderNo'],
                        "生产车间" => $info['workshop'],
                        "生产线" => $info['name'],
                        "生产线负责人" => self::findStaff($info['staffId']),
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "状态" => $info['state'],
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$word= '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '启用') {
                    $warn = "删除失败：启用中";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }  else {
            $exampleData[] = ['P001','1车间','第1生产线','样例数据，导入时请删除本条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index = 0;
            foreach ($templateField as $k=>$array){
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '生产线编号'=>$example[0],
                            '生产车间'=>$example[1],
                            '生产线'=>$example[2],
                            '备注'=>$example[3],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = $this->control['name'] . "下载了生产线导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $field = [
                        'name' => $cell['生产线'],
                        'orderNo' => $cell['生产线编号'],
                        'workshop' => $cell['生产车间'],
                        'text' =>$cell['备注'],
                    ];
                    $annotation = [
                        'name' => '生产线',
                        'orderNo' => '生产编号',
                        'workshop' => '生产车间',
                    ];
                    $rules = [
                        'name' => 'required',
                        'orderNo' => 'required',
                        'workshop' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."'  and orderNo = '$field[orderNo]'"))>0){
                        $text .= "第【{$row_list}】行：已存在此生产编号<br>";
                    }elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."'  and workshop = '$field[workshop]' and name = '$field[name]'"))>0){
                        $text .= "第【{$row_list}】行：已存在此名称的生产线<br>";
                    } else {
                        $field = array_merge($field, [
                            'id' => self::getId(),
                            'coid'=>self::$coid,
                            'stid' => $this->control['stid'],
                            'state' => '启用',
                        ]);
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }

            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'生产线编号',
                    'aliasName'=>'生产线编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产车间',
                    'aliasName'=>'生产车间',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }

}
